package com.xaw4.applejack.simulation;

import java.io.Serializable;
import java.util.ArrayList;

import android.graphics.RectF;
import android.util.Log;

public class Simulation implements Serializable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 3598283856874210342L;
	
	public static float PLAYFIELD_MIN_Y = 0;
	public static float PLAYFIELD_MAX_Y = 16;
	public static float PLAYFIELD_MIN_X = -5;
	public static float PLAYFIELD_MAX_X = 5;
	
	public static final float APPLE_LAYER = 0;
	public static final float CART_LAYER = 0;
	public static final float CART_HEIGHT = 3;
	
	public int score = 0;
	public int drops = 0;
	public float multiplier = 0.5f;
	
	public ArrayList<Apple> apples = new ArrayList<Apple>();
	
	public Cart cart;
	
	private ArrayList<Apple> removedApples= new ArrayList<Apple>();
	
	public Simulation(){
		cart = new Cart(new Vector(0, CART_HEIGHT, CART_LAYER));
		
	}
	
	public RectF getPlayfield(){
		RectF playfield = new RectF(PLAYFIELD_MIN_X, PLAYFIELD_MAX_Y, PLAYFIELD_MAX_X, PLAYFIELD_MIN_Y);
		
		return playfield;
	}
	
	public void update(float deltaTime) {
		
		updateApples(deltaTime);
		updateCart(deltaTime);
		
		checkCatch();
		
	}
	
	public void updateApples(float deltaTime){
		
		
		for (Apple apple : apples) {
			apple.update(deltaTime);
			if (apple.hasLeftField){
				dropped();
				removedApples.add(apple);
			}		
		}
		
		for (Apple apple : removedApples) {
			apples.remove(apple);
		}
		removedApples.clear();
		if(multiplier*Math.random() < 0.01){
			spawnApple();
		}
		
		
	}
	private void checkCatch(){
		for (Apple apple : apples) {
			if(cart.catchesApple(apple)){ //is this Apple catched?
				scored();
				removedApples.add(apple);
			}
		}
		for (Apple apple : removedApples) {
			apples.remove(apple);
		}
		removedApples.clear();
	}
	
	private void spawnApple() {
		float x = (float) ((  PLAYFIELD_MAX_X-PLAYFIELD_MIN_X)*Math.random() + PLAYFIELD_MIN_X);
		Apple newApple = new Apple(new Vector(x, PLAYFIELD_MAX_Y, APPLE_LAYER));
		apples.add(newApple);
	}

	private void updateCart(float deltaTime){
		
	}
	/**
	 * moves cart to new position,
	 * 0 ... leftest position
	 * 1 ... rightest position
	 * 
	 * @param pos position (1..0)
	 */
	public void moveCart(float pos){
		float x = (float) (( PLAYFIELD_MAX_X-PLAYFIELD_MIN_X)*pos + PLAYFIELD_MIN_X);
		cart.position.x = x;
	}
	
	private void scored(){
		score++;
		Log.d("Apple Jack", "scored ("+score+")");
	}
	
	private void dropped(){
		drops++;
		Log.d("Apple Jack", "apple dropped ("+drops+")");
	}
	
}
